package protoType;

import java.io.*;

public class DeepProtoType implements Serializable,Cloneable {

    public String name; // String 属性
    public DeepCloneableTarget deepCloneableTarget; //引用类型的属性

    public DeepProtoType (){
        super();
    }

    //完成深拷贝的实现 --方式1 使用clone方法


    @Override
    protected Object clone() throws CloneNotSupportedException {
        //完成对基础属性的clone（包含字符串）
        Object deep = super.clone();
        //对引用数据类型进行单独的处理
        DeepProtoType deepProtoType = (DeepProtoType)deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
        return deepProtoType;
    }


    //深拷贝 --方式2 通过对象的序列化来实现(推荐)

    public Object DeepClone(){

        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try{

            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType deepProtoType = (DeepProtoType) ois.readObject();
            return deepProtoType;

        }catch (Exception e){
            System.out.println(e.getMessage());
            return null;
        }finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                oos.close();
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
    }


}
